<?php
namespace app\index\service;
use think\Db;
use think\Loader;
class  Login{

    //短信验证发送
    function commonCodeApi($phone,$graph_code,$type=1){
     try{
        if (empty($phone)) {
            return messageInfo('101', '手机号码必需填写!');
        }
        $va_phone = preg_match('/^1\d{10}$/', $phone);
        if (!$va_phone) {
            return messageInfo('101', '手机号码格式错误');
        }

        if (!captcha_check($graph_code,1)) {
            return messageInfo('101', '图形验证码错误');
        }
        //注册 与忘记密码判断
        if ($type == 1 || $type == 2) {
            $data_phone = Db::name('user')->where('u_phone', $phone)->count();
            if ($data_phone >= 1 && $type == 1) {
                return messageInfo('101', '手机号码已经注册！');
            }else if($data_phone <= 0 && $type == 2){
                return messageInfo('101', '手机号码账号不存在！');
            }
        }
        //判断发送时间
        $user_note = Db::name('user_note');
        $where ['up_phone'] = $phone;
        $where ['up_type'] = $type;
        $up_addtime = $user_note->where($where)->order('up_addtime desc')->value('up_addtime');
        if (!empty ($n_addtime)) {
            $minute = floor((strtotime(date('Y-m-d H:i:s')) - strtotime($up_addtime)) % 86400 / 60);
            if ($minute < 1) {
                return messageInfo('101', '一分钟内只以发送1次');
            }
        }
        $current_1 = date('Y-m-d H');
        $where_1 ['DATE_FORMAT(up_addtime,"%Y-%m-%d %H")'] = array('eq', $current_1);
        $where_1 ['up_phone'] = $phone;
        $where_1 ['up_type']  = $type;
        $n_addtime_1 = $user_note->where($where_1)->count();
        if ($n_addtime_1 >= 5) {
            return messageInfo('101', '一个小时内只以发送5次');
        }
        if ($type == 1) {
            $arrt['product']  = '注册的';
        }else if($type == 2){
            $arrt['product']  = '忘记密码的';
        }
         $arrt['up_phone'] = $phone;
         $arrt['succeed']  = '验证码发送成功！';
         $arrt['errot']    = '发送的验证码，已失效';
         $arrt['up_type']  = $type;
        $response = $this->aldayu($arrt);
     } catch (\Exception $e) {
         $response = messageInfo ( '101', '服务器错误！' );
     }
        return $response;
    }


    //调用 阿里大于短信发送
    function aldayu($arrt){
        // 短信内容参数
        Loader::import('Aldy.Sms', EXTEND_PATH, '.class.php');
        $code      = randString ();
        if($arrt['up_type'] == 1){
            $AlidayuID = config('AlidayuID_ZC');
        }else{
            $AlidayuID = config('AlidayuID_PW');
        }
        $cofig ['templateCode'] = $AlidayuID;
        $sms = new \Sms($cofig);
        $smsParams = array ('code' => $code );
        $data = $sms->send_verify($arrt['up_phone'], json_encode ( $smsParams ));
        if($data['Code'] == 142 || $data['Code'] == 'isv.BUSINESS_LIMIT_CONTROL'){
            return messageInfo ( '101', '当前手机号码已被限制发送次数，重新发送验证码必需24小时之后，！' );
        }
        $user_note = Db::table( 'lt_user_note' );
        $date      = date ( 'Y-m-d H:i:s' );
        $times     = strtotime($date)+300;
        if ($data['Code'] == 'OK' && $data['Message'] == 'OK') {
            $arr = array ('up_phone' => $arrt['up_phone'],'request_id' => $data ['RequestId'], 'up_code' => $code, 'up_addtime' =>$date ,'up_type'=>$arrt['up_type'],'up_timeexpire'=>$times);
            $b = $user_note->insert ( $arr );
            if ($b) {
                $response = messageInfo ( '202', $arrt['succeed'] );
            } else {
                $response = messageInfo ( '101', $arrt['errot'] );
            }
        } else {
            $response = messageInfo ( '101', '验证码发送失败' );
        }
        return $response;
    }


    //用户注册
    function userRegisterApi($parr){
      try{
        if(empty($parr['phone']) || empty($parr['password'])){
            return messageInfo('101', '手机号码与密码必需填写!');
        }
        if(empty($parr['phone_code'])){
            return messageInfo('101', '手机短信验证码必需填写!');
        }
        $va_phone = preg_match('/^1\d{10}$/', $parr['phone']);
        if (!$va_phone) {
            return messageInfo('101', '手机号码格式错误');
        }
        if (!captcha_check($parr['graph_code'])) {
            return messageInfo('101', '图形验证码错误');
        }
       /* $password = preg_match('/(?=.*[a-z])(?=.*\d)(?=.*[#@!~%^&*])[a-z\d#@!~%^&*]{8,16}/i', $parr['password']);
        if(!$password){
            return messageInfo('101', '密码必需为数字、字母或加特殊字符组成！');
        }*/
        if(!preg_match("/^[A-Za-z0-9]+$/",$parr['password'])){
              return messageInfo('101', '密码必需为数字、字母组合！');
        }
        if(strlen($parr['password']) < 6 || strlen($parr['password']) > 16 ){
            return messageInfo('101', '密码只允许设置6~16位!');
        }

        //是否已注册过
        $user       = Db::name('user');
        $data_phone = $user->where('u_phone',$parr['phone'])->count();
        if($data_phone >= 1){
            return messageInfo('101', '手机号码已经注册过!');
        }

        //验证短信码
        $where ['up_phone'] = $parr ['phone'];
        $where ['up_type']  = 1;
        $user_note = Db::name( 'user_note' )->where ( $where )->order ( 'up_addtime desc' )->field ( 'up_code,up_timeexpire' )->find ();
        if (count ( $user_note ) < 1 || $user_note ['up_code'] != $parr ['phone_code']) {
            return messageInfo ( '101', '短信验证码错误' );
        }
        $minute = floor ( (time() - $user_note['up_timeexpire']) % 86400 / 60 );
        if ($minute > 5) {
                return messageInfo ( '101', '短信验证码超过5分钟，已失效' );
        }
        $user->startTrans();
        $u_uids =  $user->lock(true)->order('u_addtime desc')->value('u_uid');
        //写入
        $data_array = array(
            'u_phone'  => $parr ['phone'],
            'u_uid'    => $u_uids + 1,
            'u_password'  => password_hashs($parr['password']),
            'u_addtime' => date('Y-m-d H:i:s'),
        );
        $a = $user->insert($data_array);
      /*  $userId = $user->getLastInsID();*/
        if(!$a){
            $user::rollback();
            return messageInfo ( '101', '注册失败！' );
        }else{
            $user->commit();
            $response = messageInfo ( '202', '注册成功' );
        }
      /*  $u_uid = date('Ymd');
        $u_uid=$u_uid+$userId;
        $b = $user->where('user_id',$userId)->setField('u_uid',$u_uid);
        if(!$b){
            $user->rollback();
            return messageInfo ( '101', '注册失败！' );
        }*/
      } catch (\Exception $e) {
          $response = messageInfo ( '101', '服务器错误！' );
      }
      return $response;
    }


    //用户登录
    function userLogApi($parr){
        if(empty($parr['number']) || empty($parr['password'])){
            return messageInfo('101', '账号与密码必需填写!');
        }
        $lt_user = session('lt_user');
        if($lt_user && $lt_user['u_phone'] == $parr['number']){
            return messageInfo('101', '你已登录了,请别重复登录!');
        }
        $user       = Db::name('user');
        $data_user  = $user->where('u_phone',$parr['number'])->field('u_uid,u_mail,u_phone,u_nickname,u_img,u_password')->find();
        if(empty($data_user)){
            return messageInfo('101', '账号不存在!');
        }
        if(empty($data_user['u_password'])){
            return messageInfo('101', '密码为空，请先去重置密码!');
        }
        if(!password_verifys($parr['password'],$data_user['u_password'])){
            return messageInfo('101', '密码错误!');
        }
        $data_array = array(
            'u_uid'  => $data_user ['u_uid'],
            'ul_ip'  => get_client_ip_c(),//查询ip地址
            'ul_addtime' => date('Y-m-d H:i:s'),
        );
        $a = Db::name('user_log')->insert($data_array);
        if(!$a){
            return messageInfo ( '101', '登录失败！' );
        }
        session('lt_user',$data_user);
        return messageInfo ( '202', '登录成功！' );
    }


    //忘记密码
    function forgetSetPasswordApi($parr){
        try{
            if(empty($parr['phone']) || empty($parr['password'])){
                return messageInfo('101', '手机号码与密码必需填写!');
            }
            if(empty($parr['phone_code'])){
                return messageInfo('101', '手机短信验证码必需填写!');
            }
            $va_phone = preg_match('/^1\d{10}$/', $parr['phone']);
            if (!$va_phone) {
                return messageInfo('101', '手机号码格式错误');
            }

            if (!captcha_check($parr['graph_code'],2)) {
                return messageInfo('101', '图形验证码错误');
            }
            if(!preg_match("/^[A-Za-z0-9]+$/",$parr['password'])){
                return messageInfo('101', '密码必需为数字、字母组合！');
            }
            if(strlen($parr['password']) < 6 || strlen($parr['password']) > 16 ){
                return messageInfo('101', '密码只允许设置6~16位!');
            }
            $user       = Db::name('user');
            $data_user = $user->where('u_phone',$parr ['phone'])->field('u_password,u_phone')->find();
            if(empty($data_user))  return messageInfo('101', '账号不存在！');
            $u_password =  $data_user['u_password'];
            if(!empty($u_password) && password_verifys($parr['password'],$u_password)){
                return messageInfo('101', '新密码不能与旧密码一致！');
            }
            $password   = password_hashs($parr['password']);
         /*   if($u_password == $password){
                return messageInfo('101', '新密码不能与旧密码一致！');
            }*/
            //验证短信码
            $where ['up_phone'] = $parr ['phone'];
            $where ['up_type']  = 2;
            $user_note = Db::name('user_note')->where ( $where )->order ( 'up_addtime desc' )->field ( 'up_code,up_timeexpire' )->find ();
            if (count ( $user_note ) < 1 || $user_note ['up_code'] != $parr ['phone_code']) {
                return messageInfo ( '101', '短信验证码错误' );
            }
            $minute = floor ( (time() - $user_note['up_timeexpire']) % 86400 / 60 );
            if ($minute > 5) {
                return messageInfo ( '101', '短信验证码超过5分钟，已失效' );
            }
            $b = $user->where('u_phone',$parr ['phone'])->setField('u_password',$password);
            if(!$b){
                return messageInfo ( '101', '重置失败！' );
            }
            $response = messageInfo ( '202', '重置成功' );
        } catch (\Exception $e) {
            $response = messageInfo ( '101', '服务器错误！' );
        }
        return $response;
    }


    //文书下载
    function docDownloadApi($writ_id){
        try{
            if(empty($writ_id)){
               exit('数据错误');
            }
            $writ = Db::name('writ');
            $w_writ_data  = Db::name('writ')->where('writ_id',$writ_id)->field('w_writ_url,w_title')->find();
            if(empty($w_writ_data['w_writ_url'])){
                exit('文书不存在!');
            }
            $w_writ_url = $w_writ_data['w_writ_url'];
            header("Content-type:text/html;charset=utf-8");
            //用以解决中文不能显示出来的问题
            $file_path = ROOT_PATH . 'public' . DS . $w_writ_url;
            $explode  = explode('.',$file_path);
            $filename = preg_replace('/[ ]/', '', $w_writ_data['w_title']).'.'.$explode[1];
            //首先要判断给定的文件存在与否
            if (!file_exists($file_path)) {
                exit('文书不存在!');
            }
            $writ->startTrans();
            $a = $writ->where('writ_id',$writ_id)->setInc('w_download_sum');
            if(!$a){
                $writ->rollback();
                exit('下载失败!');
            }
            /* 方法一；header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file_path));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file_path));
            Header("Content-Disposition: attachment; filename=" .$filename);
            readfile($file_path);*/

            //方法二
            $fp = fopen($file_path, "r");
            $file_size = filesize($file_path);
            //下载文件需要用到的头
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length:" . $file_size);
            Header("Content-Disposition: attachment; filename=" .$filename);
            $buffer = 1024;
            $file_count = 0;
            //向浏览器返回数据
            while (!feof($fp) && $file_count < $file_size) {
                $file_con = fread($fp, $buffer);
                $file_count += $buffer;
                echo $file_con;
            }
            $writ->commit();
            fclose($fp);
            exit;
        } catch (\Exception $e) {
            exit('服务器错误');
        }
    }

}
